<!-- css -->
<!-- Datatables -->
<link href="cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" />
<link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet" />
<!-- NProgress -->
<link href="/vendors/nprogress/nprogress.css" rel="stylesheet" />
<!-- 上传图片 -->
<link href="/vendors/fileinput/fileinput.min.css" rel="stylesheet" />

<div class="page-title">
	<div class="title_left">
		<h3>Users <small>list page</small></h3>
	</div>
</div>

<div class="clearfix"></div>

<div class="row" id="usersModel">
	<div class="col-md-12 col-sm-12">
		<div class="x_panel">
			<div class="x_title">
				<!-- <h2>Default Example <small>Users</small></h2> -->
				<button
					@click="initAddModal()"
					class="btn btn-primary"
					type="button"
					data-toggle="modal"
					data-target="#modalAdd"
				>
					新增
				</button>
				<ul class="nav navbar-right panel_toolbox">
					<li>
						<a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
					</li>
					<li class="dropdown">
						<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"
							><i class="fa fa-wrench"></i
						></a>
						<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
							<a class="dropdown-item" href="#">Settings 1</a>
							<a class="dropdown-item" href="#">Settings 2</a>
						</div>
					</li>
					<li>
						<a class="close-link"><i class="fa fa-close"></i></a>
					</li>
				</ul>
				<div class="clearfix"></div>
			</div>
			<div class="x_content">
				<div class="row">
					<div class="col-sm-12">
						<div class="card-box table-responsive">
							<table id="modelTable" class="table table-striped table-bordered" style="width: 100%">
								<thead>
									<tr>
										<th>id</th>
										<th>UserName</th>
										<th>Password</th>
										<th>UserImage</th>
										<th>CreateDate</th>
										<th>Operate</th>
									</tr>
								</thead>
								<tbody></tbody>
							</table>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- 引入模态框 -->
	<div th:replace="account/userAdd"></div>
	<div th:replace="account/userEdit"></div>
</div>

<!-- Datatables -->
<script src="/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<!-- NProgress -->
<script src="/vendors/nprogress/nprogress.js" type="text/javascript"></script>
<!-- morris.js -->
<script src="/vendors/raphael/raphael.min.js" type="text/javascript"></script>
<script src="/vendors/morris.js/morris.min.js" type="text/javascript"></script>
<!-- bootstrap-progressbar -->
<script src="/vendors/bootstrap-progressbar/bootstrap-progressbar.min.js" type="text/javascript"></script>
<!-- 上传图片 -->
<script src="/vendors/fileinput/fileinput.min.js" type="text/javascript"></script>

<script>
	var usersVue = new Vue({
		el: "#usersModel",
		data: {
			user: {
				id: 0,
				createDate: "",
				userName: "",
				password: "",
				userImage: "",
				roles: [],
			},
			roles: [],
			search: {
				currentPage: 1,
				pageSize: 5,
				sort: "id",
				direction: "desc",
				keyword: "",
			},
			// 表格数据结构
			tableData: {
				draw: 0,
				recordsTotal: 0,
				recordsFiltered: 0,
				data: [],
			},
			defaultPageSize: 5,
		},
		methods: {
			// 行数据结构
			rowData: function (id, userName, password, userImage, createDate) {
				var row = {};
				row.id = id;
				row.userName = userName;
				row.password = password;
				row.userImage = userImage;
				row.createDate = createDate;
				row.operate = function () {
					return (
						"<a class='btn_editcolor' onclick='initModel(" +
						id +
						")' data-toggle='modal' data-target='#modalEdit'>修改</a>&nbsp;&nbsp;" +
						"<a class='btn_editcolor' onclick='deleteModel(" +
						id +
						")'>删除</a>"
					);
				};
				return row;
			},
			initDataTable: function (pageSize) {
				var self = this;
				self.dataTable = $("#modelTable").DataTable({
					paging: true, //分页
					serverSide: true, //开启后端分页
					pagingType: "full_numbers", //分页样式的类型simple/simple_numbers/full/full_numbers
					pageLength: pageSize, //定义初始的页长
					processing: true,
					destroy: true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
					lengthChange: true, //控制是否能够调整每页的条数
					lengthMenu: [5, 10, 25, 50], // 控制页长
					searching: true,
					"data-show-refresh": true,
					ordering: true,
					order: [0, "desc"], // 默认第 0 列倒叙排列
					autoWidth: true,
					ajax: function (data, callback, settings) {
						// 从data获取查询数据
						var columIndex = data.order[0].column;
						var direction = data.order[0].dir;
						var sort = data.columns[columIndex].name;
						pageSize = data.length == undefined ? pageSize : data.length;

						self.search.currentPage = data.start / pageSize + 1;
						self.search.pageSize = pageSize;
						self.search.sort = sort;
						self.search.direction = direction;
						self.search.keyword = data.search.value;

						$.ajax({
							url: "/api/users",
							type: "post",
							contentType: "application/json",
							data: JSON.stringify(self.search),
							success: function (rs) {
								if (!rs) {
									layer.alert("请求出错，请稍后重试" + rs.errmsg, { icon: 2 });
									callback(self.tableData);
									return;
								}
								if (rs.list == null) {
									$("#moduleTable tbody tr").remove();
									$("#loading").remove();
									callback(self.tableData);
									return;
								}
								$("#loading").remove();
								var rowsData = [];
								$.each(rs.list, function (i, item) {
									//包装行数据
									var rowData = self.rowData(
										item.id,
										item.userName,
										item.password,
										item.userImage,
										item.createDate
									);
									// 将行数据放到数组里
									rowsData.push(rowData);
								});
								self.tableData.data = rowsData;
								self.tableData.recordsTotal = rs.total;
								self.tableData.recordsFiltered = rs.total;
								callback(self.tableData);
							},
							error: function (data) {
								layer.alert(data.responseText, { icon: 0 });
							},
						});
					},
					columns: [
						//定义行数据字段
						{ data: "id", name: "id", sortable: true },
						{ data: "userName", name: "user_name", sortable: true },
						{ data: "password", name: "password", sortable: true },
						{ data: "userImage", name: "userImage", sortable: true },
						{ data: "createDate", name: "create_date", sortable: true },
						{ data: "operate", width: "80px", sortable: false },
					],
				});
			},
			initFileUpload: function () {
				var self = this;
				$("#uploadImage")
					.fileinput({
						uploadUrl: "/api/image/profile-big",
						enctype: "multipart/form-data",
						previewFileType: "image",
						uploadAsync: true,
						allowedFileExtensions: ["png", "jpg", "jpeg", "ico", "bmp", "gif"],
						maxFileCount: 1,
						maxFileSize: 3072,
						minImageWidth: 50,
						minImageHeight: 50,
						maxImageWidth: 1000,
						maxImageHeight: 1000,
						msgFilesTooMany: "Upload file count({n} - {m})",
						showCaption: false,
						dropZoneEnabled: false,
						showBrowse: true,
						browseClass: "btn btn-primary",
						uploadClass: "btn btn-info",
						removeClass: "btn btn-danger",
					})
					.on("fileerror", function (event, data, msg) {
						layer.alert("Upload file failed" + msg, { icon: 0 });
					})
					.on("fileuploaded", function (event, data) {
						if (data.response.status == 200) {
							self.user.userImage = data.response.data;
						}
						$(".fileinput-remove-button").click();
						layer.alert(data.response.message, { icon: 0 });
					})
					.on("fileclear", function (event) {});
			},
			initRoles: function () {
				var self = this;
				$.ajax({
					url: "/api/roles",
					type: "get",
					success: function (rs) {
						self.roles = rs;
					},
					error: function () {
						layer.alert("服务器错误", { icon: 0 });
					},
				});
			},
			initAddModal: function () {
				this.user = {
					id: 0,
					createDate: "",
					userName: "",
					password: "",
					userImage: "",
					roles: [],
				};
			},
			addModel: function () {
				var self = this;
				self.user.roles = self.user.roles.map((item) => {
					var role = {};
					role.id = item;
					return role;
				});
				console.log(self.user);
				$.ajax({
					url: "/api/user",
					type: "post",
					contentType: "application/json",
					data: JSON.stringify(self.user),
					success: function (rs) {
						if (rs.status == 200) {
							$("#modalAdd").modal("hide");
							self.initDataTable(self.defaultPageSize);
						} else {
							layer.alert(rs.message, { icon: 0 });
						}
					},
					error: function () {
						layer.alert("服务器错误", { icon: 0 });
					},
				});
			},
			initModel: function (id) {
				var self = this;
				$.ajax({
					url: "/api/user/" + id,
					type: "get",
					success: function (rs) {
						self.user = rs;
						self.user.roles = self.user.roles.map((item) => {
							return item.id;
						});
					},
					error: function () {
						layer.alert("服务器错误", { icon: 0 });
					},
				});
			},
			updateModel: function () {
				var self = this;
				self.user.roles = self.user.roles.map((item) => {
					var role = {};
					role.id = item;
					return role;
				});
				console.log(self.user);
				$.ajax({
					url: "/api/user",
					type: "put",
					contentType: "application/json",
					data: JSON.stringify(self.user),
					success: function (rs) {
						if (rs.status == 200) {
							$("#modalEdit").modal("hide");
							self.initDataTable(self.defaultPageSize);
						} else {
							layer.alert(rs.message, { icon: 0 });
						}
					},
					error: function () {
						layer.alert("服务器错误", { icon: 0 });
					},
				});
			},
			deleteModel: function (id) {
				var self = this;
				bootbox.confirm("Are you sure?", function (result) {
					if (result) {
						$.ajax({
							url: "/api/user/" + id,
							type: "delete",
							success: function (rs) {
								if (rs.status == 200) {
									self.initDataTable(self.defaultPageSize);
								} else {
									layer.alert(rs.message, { icon: 0 });
								}
							},
							error: function (data) {
								layer.alert(data.responseText, { icon: 0 });
							},
						});
					}
				});
			},
		},
		created() {
			window.initModel = this.initModel;
			window.deleteModel = this.deleteModel;
		},
		mounted() {
			this.initDataTable(this.defaultPageSize);
			this.initFileUpload();
			this.initRoles();
		},
	});
</script>
